﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace EventLogAdmin
{
    public partial class AddEventSourceForm : Form
    {
        public AddEventSourceForm()
        {
            InitializeComponent();
        }

        public DialogResult AddSource(string machineName, string eventLogName)
        {
            txtComputer.Text = machineName;
            txtEventLog.Text = eventLogName;
            return ShowDialog();
        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            if (txtEventSource.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must specify a valid string!", "Event source create", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtEventSource.Focus();
            }
            else if (EventLog.SourceExists(txtEventSource.Text, txtComputer.Text))
            {

                MessageBox.Show("The Event Source exists already!\r\nLog: " + EventLog.LogNameFromSourceName(txtEventSource.Text, txtComputer.Text), "Event source create", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtEventSource.Focus();
            }
            else
            {
                try
                {
                    EventLog.CreateEventSource(txtEventSource.Text, txtEventLog.Text, txtComputer.Text);
                    if (txtEventLog.Text != "Security" && (txtComputer.Text == "." || System.Net.Dns.GetHostName().ToUpper() == txtComputer.Text.ToUpper()))
                        EventLog.WriteEntry(txtEventSource.Text, "Event source created");
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                    Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Event source create", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}
